package vn.com.hung.notetaker.abstractMenus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTable;

import vn.com.hung.notetaker.abstractModels.NoteTableModel;
import vn.com.hung.notetaker.utils.XMLFilter;

@SuppressWarnings("serial")
public class NoteViewMenu extends JMenuBar implements ActionListener{
    
    private JTable table;
    
    private JMenu fileMenu = new JMenu("File");
    private JMenuItem loadItem = new JMenuItem("Load Data");
    private JMenuItem saveAsItem = new JMenuItem("Save As");
    
    
    public NoteViewMenu(JTable bookTable) {
        this.table = bookTable;
        add(fileMenu);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        fileMenu.add(loadItem);
        fileMenu.add(saveAsItem);
        loadItem.setMnemonic(KeyEvent.VK_L);
        loadItem.addActionListener(this);
        
        saveAsItem.setMnemonic(KeyEvent.VK_S);
        saveAsItem.addActionListener(this);
    }
    
   
    @Override
    public void actionPerformed(ActionEvent arg0) {
        JMenuItem item = (JMenuItem) arg0.getSource();
        if (item.equals(loadItem)) {
            System.out.println("process load");
            // process choose file
            JFileChooser c = new JFileChooser();
            c.setFileFilter(new XMLFilter());
            int returnValue = c.showOpenDialog(getParent());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = c.getSelectedFile();
                try {
                    ((NoteTableModel) table.getModel()).loadCSV(selectedFile.getAbsolutePath());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                table.updateUI();
              }
        } else if (item.equals(saveAsItem)) {
            // process save as 
            JFileChooser c = new JFileChooser();
            c.setFileFilter(new XMLFilter());
            int returnValue = c.showSaveDialog(getParent());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                String fileName = c.getSelectedFile().getPath();
                if (!fileName.endsWith(".xml")) {
                    fileName += ".xml";
                }
                try {
                    ((NoteTableModel) table.getModel()).saveToCSV(fileName);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    
   
    

}
